//
//  Problem59.swift
//  TestProject
//
//  Created by 武侠 on 2021/5/14.
//  Copyright © 2021 zhulong. All rights reserved.
//

import UIKit

/*
 给你一个正整数 n，生成一个包含 1 ～ n的平方 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

 示例 1：
  1 -> 2 -> 3
           \|/
  8 -> 9    4
 /|\       \|/
  7 <- 6 <- 5
     输入：n = 3
     输出：[[1,2,3],[8,9,4],[7,6,5]]
 示例 2：
     输入：n = 1
     输出：[[1]]
 提示：
    1 <= n <= 20
 */
@objcMembers class Problem59: NSObject {
    func solution() {
        print(generateMatrix(8))
    }
    
    /*
     按照题意遍历
     */
    func generateMatrix(_ n: Int) -> [[Int]] {
        var list = Array(repeating: Array(repeating: 0, count: n), count: n)
        // 0: 左->右 1:上->下 2: 右->左 3: 下->上
        var direct  = 0
        var start   = 0
        var end     = n-1
        var row     = 0
        
        var i = 1
        while i <= n * n {
            if direct == 0 {            // 0: 左->右
                for j in start...end  {
                    list[row][j] = i
                    i += 1
                }
                direct = 1
                start = row + 1
                row = end
                end = n - start
            } else if direct == 1 {     // 1:上->下
                for j in start...end {
                    list[j][row] = i
                    i += 1
                }
                direct = 2
                start = row - 1
                row = end
                end = n - start - 1 - 1
            } else if direct == 2 {     // 2: 右->左
                for j in (end...start).reversed() {
                    list[row][j] = i
                    i += 1
                }
                direct = 3
                start = row - 1
                row = end
                end = row + 1
            } else {
                for j in (end...start).reversed() {
                    list[j][row] = i
                    i += 1
                }
                direct = 0
                start = row + 1
                row = end
                end = n - start - 1
            }
        }
        
        
        return list
    }
}

/*
 [1,  2,  3,  4,  5]
 [16, 17, 18, 19, 6]
 [15, 24, 25, 20, 7]
 [14, 23, 22, 21, 8]
 [13, 12, 11, 10, 9]
 */
